package com.silverhaze.diamond.client.ui;

import com.silverhaze.commons.db.datasource.ObjectEntity;
import com.silverhaze.commons.helpers.CommonUIHelper;
import com.silverhaze.diamond.client.Application;
import com.silverhaze.diamond.client.common.AuroraConstants;
import com.silverhaze.diamond.client.data.SpecificData;
import com.silverhaze.diamond.client.data.dao.DAOLocator;
import com.silverhaze.diamond.client.resources.ServiceResourceContainer;
import com.silverhaze.diamond.client.settings.SettingsStorage;
import com.silverhaze.diamond.client.settings.ui.MainFrameSettings;
import com.silverhaze.diamond.client.ui.builders.MenuBarBuilder;
import com.silverhaze.diamond.client.ui.builders.TrayIconBuilder;
import com.silverhaze.diamond.client.ui.dialogs.*;
import com.silverhaze.diamond.client.ui.dialogs.view.ViewDialog;
import com.silverhaze.diamond.client.ui.event.UIClientEventDispatcher;
import com.silverhaze.diamond.client.ui.event.UIEventDispatcherListener;
import com.silverhaze.diamond.client.ui.event.UIUpdateEntitiesEvent;
import com.silverhaze.diamond.client.ui.filter.CustomersFilterPanel;
import com.silverhaze.diamond.client.ui.filter.DetailsFilterPanel;
import com.silverhaze.diamond.client.ui.filter.ServiceFilterPanel;
import com.silverhaze.diamond.client.ui.frame.AbstractFrame;
import com.silverhaze.diamond.client.ui.report.ReportViewer;
import com.silverhaze.diamond.client.ui.table.CustomersTable;
import com.silverhaze.diamond.client.ui.table.DetailsTable;
import com.silverhaze.diamond.client.ui.table.ServiceTable;
import com.silverhaze.diamond.client.ui.table.model.CustomersTableModel;
import com.silverhaze.diamond.client.ui.table.model.DetailsTableModel;
import com.silverhaze.diamond.client.ui.table.model.ServiceTableModel;
import com.silverhaze.diamond.common.entity.Customer;
import com.silverhaze.diamond.common.entity.Detail;
import com.silverhaze.diamond.common.entity.Service;
import com.silverhaze.diamond.common.entity.SystemUser;
import com.silverhaze.diamond.common.event.UIEvent;
import com.silverhaze.diamond.common.event.UIEventClassChanged;
import com.silverhaze.diamond.common.event.UIEventEntityChanged;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRTableModelDataSource;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.io.InputStream;
import java.util.*;
import java.util.List;


/**
 * Created by Ivan Babanin
 * This part of code is strictly confidential.
 * ? Magnificent Software Inc.
 */
public class MainFrame extends AbstractFrame implements UIEventDispatcherListener {
    private JButton addServiceButton;
    private JButton copyServiceButton;
    private JButton deleteServiceButton;
    private JButton editServiceButton;

    private JButton addCustomerButton;
    private JButton editCustomerButton;
    private JButton deleteCustomerButton;

    private JButton addDetailButton;
    private JButton editDetailButton;
    private JButton deleteDetailButton;

    private JButton refreshButton;
    private JButton viewButton;
    private JButton printButton;

    private JPanel emptyPanel;
    private JPanel serviceCompletePanel;
    private JButton serviceCompleteButton;
    private JButton clientTookStuffButton;

    private List<JButton> buttonControl;

    private JToggleButton filterButton;

    private JTabbedPane tabPane;

    private JTable serviceTable;
    private JTable customersTable;
    private JTable detailsTable;

    private JLabel serviceLabel;
    private JLabel customerLabel;
    private JLabel detailsLabel;

    private ServiceFilterPanel serviceFilterPanel;
    private CustomersFilterPanel customersFilterPanel;
    private DetailsFilterPanel detailsFilterPanel;

    private ServiceTableModel serviceTableModel;
    private CustomersTableModel customersTableModel;
    private DetailsTableModel detailsTableModel;

    private Service selectedService;
    private Customer selectedCustomer;
    private Detail selectedDetail;

    private static final int SERVICE_TAB_ID = 0;
    private static final int CUSTOMER_TAB_ID = 1;
    private static final int DETAIL_TAB_ID = 2;

    private JProgressBar progressBar;

    public MainFrame() {
        UIClientEventDispatcher.getInstance().subscribe(this, UIUpdateEntitiesEvent.class,
                UIEventEntityChanged.class, UIEventClassChanged.class);
    }

    private Dimension calculateDimension(MainFrameSettings mainFrameSettings) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        int width = mainFrameSettings.getWidth();
        int height = mainFrameSettings.getHeight();

        width = width > screenSize.getWidth() ? (int) screenSize.getWidth() : width;
        height = height > screenSize.getHeight() ? (int) screenSize.getHeight() : height;

        return new Dimension(width, height);
    }

    protected void init() {
        super.init();

        UIClientEventDispatcher.getInstance().subscribe(new UIEventDispatcherListener() {
            @Override
            public void handleEvent(UIEvent event) {
                Class<? extends ObjectEntity> clazz = event.getChangedEntityClass();

                if (Service.class.equals(clazz)) {
                    updateServiceLabel();
                } else if (Customer.class.equals(clazz)) {
                    updateCustomerLabel();
                } else if (Detail.class.equals(clazz)) {
                    updateDetailsLabel();
                }
            }
        }, UIEventEntityChanged.class, UIEventClassChanged.class);

        setPreferredSize(new Dimension(1024, 768));

        setTitle(UIHelper.getCaption());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                Application.finish();
            }
        });

        setJMenuBar(MenuBarBuilder.build());
        TrayIconBuilder.build();

        add(initializeButtonBar(), BorderLayout.PAGE_END);
        add(initializeMainPanel(), BorderLayout.CENTER);

        pack();
        setLocationRelativeTo(null);
    }

    private JPanel initializeMainPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        tabPane = new JTabbedPane();
        tabPane.addTab(UIStringConstants.SERVICE + " ", ServiceResourceContainer.SERVICE_N, serviceTab());
        tabPane.addTab(UIStringConstants.CUSTOMERS + " ", ServiceResourceContainer.MAN, customersTab());
        tabPane.addTab(UIStringConstants.DETAILS + " ", ServiceResourceContainer.SERVICE, detailsTab());

        tabPane.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                switch (tabPane.getSelectedIndex()) {
                    case SERVICE_TAB_ID:
                        serviceTabSelected();
                        break;
                    case CUSTOMER_TAB_ID:
                        customersTabSelected();
                        break;
                    case DETAIL_TAB_ID:
                        detailsTabSelected();
                        break;
                }
            }
        });

        panel.add(tabPane, BorderLayout.CENTER);
        return panel;
    }

    private void detailsTabSelected() {
        buttonControl(selectedDetail != null);
        serviceCompletePanel.setVisible(false);
        emptyPanel.setVisible(true);
    }

    private void customersTabSelected() {
        buttonControl(selectedCustomer != null);
        serviceCompletePanel.setVisible(false);
        emptyPanel.setVisible(true);
    }

    private void serviceTabSelected() {
        buttonControl(selectedService != null);
        serviceCompletePanel.setVisible(true);
        emptyPanel.setVisible(false);
    }

    private JPanel detailsTab() {
        JPanel panel = new JPanel(new BorderLayout());

        JPanel tablePanel = new JPanel(new BorderLayout());
        tablePanel.setBorder(new TitledBorder(" " + UIStringConstants.DETAILS + " "));
        detailsTableModel = new DetailsTableModel();

        detailsTable = new DetailsTable(detailsTableModel);
        detailsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                int row = detailsTable.getSelectedRow();

                if (row >= 0 && row < detailsTableModel.getRowCount()) {
                    selectedDetail = detailsTableModel.getObjectAtRow(row);
                    buttonControl(true);
                }
            }
        });

        tablePanel.add(new JScrollPane(detailsTable), BorderLayout.CENTER);

        detailsFilterPanel = new DetailsFilterPanel(detailsTableModel, filterButton);
        if (filterButton.isSelected()) {
            detailsFilterPanel.setVisible(true);
        } else {
            detailsFilterPanel.setVisible(false);
        }

        panel.add(createDetailInfoPanel(), BorderLayout.PAGE_START);
        panel.add(tablePanel, BorderLayout.CENTER);
        panel.add(detailsFilterPanel, BorderLayout.PAGE_END);

        return panel;
    }

    private JPanel createDetailInfoPanel() {
        JPanel result = new JPanel(new BorderLayout());

        addDetailButton = new JButton(new AbstractAction("Добавить", ServiceResourceContainer.PLUS) {
            @Override
            public void actionPerformed(ActionEvent e) {
                DetailDialog.createDetail(MainFrame.this, null);
                detailsFilterPanel.applyData();
            }
        });

        editDetailButton = new JButton(new AbstractAction("Редактировать", ServiceResourceContainer.EDIT_ICON) {
            @Override
            public void actionPerformed(ActionEvent e) {
            }
        });

        deleteDetailButton = new JButton(new AbstractAction("Удалить", ServiceResourceContainer.DELETE_ICON) {
            @Override
            public void actionPerformed(ActionEvent e) {
            }
        });

        detailsLabel = new JLabel();
        detailsLabel.setToolTipText("<html><font color=green>завершено</font> / " +
                "<font color=red>в ремонте</font> / All</html>");
        updateDetailsLabel();

        result.add(detailsLabel, BorderLayout.LINE_START);
        result.add(UIHelper.hBox(addDetailButton, 5, editDetailButton, 5, deleteDetailButton, 7), BorderLayout.LINE_END);

        JPanel panel = CommonUIHelper.packInTitledPanel(result, BorderLayout.CENTER, " Information ");
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        return panel;
    }

    private JPanel customersTab() {
        JPanel panel = new JPanel(new BorderLayout());

        JPanel tablePanel = new JPanel(new BorderLayout());
        tablePanel.setBorder(new TitledBorder(" " + UIStringConstants.CUSTOMERS + " "));
        customersTableModel = new CustomersTableModel();

        customersTable = new CustomersTable(customersTableModel);
        customersTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                int row = e.getFirstIndex();

                if (row >= 0 && row < customersTableModel.getRowCount()) {
                    selectedCustomer = customersTableModel.getObjectAtRow(row);
                    buttonControl(true);
                }
            }
        });

        tablePanel.add(new JScrollPane(customersTable), BorderLayout.CENTER);

        customersFilterPanel = new CustomersFilterPanel(customersTableModel, filterButton);
        if (filterButton.isSelected()) {
            customersFilterPanel.setVisible(true);
        } else {
            customersFilterPanel.setVisible(false);
        }

        panel.add(createCustomerInfoPanel(), BorderLayout.PAGE_START);
        panel.add(tablePanel, BorderLayout.CENTER);
        panel.add(customersFilterPanel, BorderLayout.PAGE_END);

        return panel;
    }

    private JPanel createCustomerInfoPanel() {
        JPanel result = new JPanel(new BorderLayout());

        addCustomerButton = new JButton(new AbstractAction("Добавить", ServiceResourceContainer.PLUS) {
            @Override
            public void actionPerformed(ActionEvent e) {
                CustomerDialog.createCustomer(MainFrame.this);
                customersFilterPanel.applyData();
            }
        });

        editCustomerButton = new JButton(new AbstractAction("Редактировать", ServiceResourceContainer.EDIT_ICON) {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (selectedCustomer != null) {
                    CustomerDialog.editCustomer(MainFrame.this, selectedCustomer);
                }
            }
        });

        deleteCustomerButton = new JButton(new AbstractAction("Удалить", ServiceResourceContainer.DELETE_ICON) {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (selectedCustomer != null) {
                    DAOLocator.getInstance().remove(selectedCustomer);
                }
            }
        });

        customerLabel = new JLabel();
        customerLabel.setToolTipText("<html><font color=green>завершено</font> / " +
                "<font color=red>в ремонте</font> / All</html>");
        updateCustomerLabel();

        result.add(customerLabel, BorderLayout.LINE_START);
        result.add(UIHelper.hBox(addCustomerButton, 5, editCustomerButton, 5, deleteCustomerButton), BorderLayout.LINE_END);

        JPanel panel = CommonUIHelper.packInTitledPanel(result, BorderLayout.CENTER, " Information ");
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        return panel;
    }

    private JPanel serviceTab() {
        JPanel panel = new JPanel(new BorderLayout());

        JPanel tablePanel = new JPanel(new BorderLayout());

        JPanel topTablePanel = new JPanel(new BorderLayout());
        topTablePanel.add(new JButton("+"), BorderLayout.LINE_END);

        tablePanel.setBorder(new TitledBorder(" " + UIStringConstants.SERVICE + " "));
        serviceTableModel = new ServiceTableModel();

        serviceTable = new ServiceTable(serviceTableModel);
        serviceTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                int row = serviceTable.getSelectedRow();

                if (row >= 0 && row < serviceTableModel.getRowCount()) {
                    selectedService = serviceTableModel.getObjectAtRow(row);

                    buttonControl(true);

                    if (selectedService.isServiceComplete()) {
                        clientTookStuffButton.setEnabled(true);
                        serviceCompleteButton.setEnabled(false);
                    } else {
                        serviceCompleteButton.setEnabled(true);
                        clientTookStuffButton.setEnabled(false);
                    }

                    if (selectedService.isClientTookStuff()) {
                        clientTookStuffButton.setEnabled(false);
                    }

                    if (noRights(selectedService)) {
                        editServiceButton.setEnabled(false);
                        deleteServiceButton.setEnabled(false);
                        serviceCompleteButton.setEnabled(false);
                        clientTookStuffButton.setEnabled(false);
                    }
                }
            }
        });

        serviceTableModel.addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                buttonControl(false);
            }
        });

        tablePanel.add(new JScrollPane(serviceTable), BorderLayout.CENTER);

        serviceTable.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() >= 2) {
                    Service service = serviceTableModel.getObjectAtRow(serviceTable.getSelectedRow());

                    if (!service.isServiceComplete()) {
                        serviceCompleteButton.setEnabled(true);
                    }
                }
            }
        });

        serviceFilterPanel = new ServiceFilterPanel(serviceTableModel, filterButton);
        if (filterButton.isSelected()) {
            serviceFilterPanel.setVisible(true);
        } else {
            serviceFilterPanel.setVisible(false);
        }

        panel.add(initServiceInfo(), BorderLayout.PAGE_START);
        panel.add(tablePanel, BorderLayout.CENTER);
        panel.add(serviceFilterPanel, BorderLayout.PAGE_END);

        return panel;
    }

    private boolean noRights(Service selectedService) {
        SystemUser user = SettingsStorage.getUserSettings().getCurrentUser();
        return !(user.equals(selectedService.getSystemUser()) || user.isAdmin());
    }

    private JComponent initServiceInfo() {
        JPanel result = new JPanel(new BorderLayout());

        serviceLabel = new JLabel();
        serviceLabel.setToolTipText("<html><font color=green>завершено</font> / " +
                "<font color=red>в ремонте</font> / All</html>");
        updateServiceLabel();

        result.add(serviceLabel, BorderLayout.LINE_START);
        result.add(UIHelper.hBox(addServiceButton, 5, copyServiceButton, 5, 5, editServiceButton, 5, deleteServiceButton, 7), BorderLayout.LINE_END);

        JPanel panel = CommonUIHelper.packInTitledPanel(result, BorderLayout.CENTER, " Information ");
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        return panel;
    }

    private void updateServiceLabel() {
        int allServicesCount = SpecificData.getAllServicesCount();
        int completedServiceCount = SpecificData.getCompletedServiceCount();
        int uncompletedServiceCount = allServicesCount - completedServiceCount;

        serviceLabel.setText("<html><b>Сервисы: " +
                "<font color='green'>" + completedServiceCount + "</font> / " +
                "<font color='red'>" + uncompletedServiceCount + "</font> / " +
                allServicesCount + "</b></html>");
    }

    private void updateCustomerLabel() {
        customerLabel.setText("<html><b>Покупатели: " + DAOLocator.getInstance().getCustomers().size() + "</b></html>");
    }

    private void updateDetailsLabel() {
        detailsLabel.setText("<html><b>Детали: " + DAOLocator.getInstance().getDetails().size() + "</b></html>");
    }

    private JPanel initializeButtonBar() {
        JPanel panel = new JPanel(new BorderLayout());

        progressBar = new JProgressBar();

        filterButton = new JToggleButton(ServiceResourceContainer.FILTER);
        filterButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                serviceFilterPanel.setVisible(!serviceFilterPanel.isVisible());
                customersFilterPanel.setVisible(!customersFilterPanel.isVisible());
                detailsFilterPanel.setVisible(!detailsFilterPanel.isVisible());
            }
        });

        viewButton = new JButton("Просмотреть", ServiceResourceContainer.VIEW);
        addToButtonControl(viewButton);
        viewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                switch (tabPane.getSelectedIndex()) {
                    case SERVICE_TAB_ID:
                        ViewDialog.service(selectedService);
                        break;
                    case CUSTOMER_TAB_ID:
                        ViewDialog.customer(selectedCustomer);
                        break;
                    case DETAIL_TAB_ID:
                        ViewDialog.detail(selectedDetail);
                        break;
                }
            }
        });

        addServiceButton = new JButton(new AbstractAction("Добавить", ServiceResourceContainer.PLUS) {
            public void actionPerformed(ActionEvent e) {
                ServiceDialog.createService();
                serviceFilterPanel.applyData();
            }
        });

        copyServiceButton = new JButton(new AbstractAction("Копировать", ServiceResourceContainer.COPY) {
            public void actionPerformed(ActionEvent e) {
                switch (tabPane.getSelectedIndex()) {
                    case SERVICE_TAB_ID:
                        ServiceDialog.createClone(selectedService);
                        break;
                    case CUSTOMER_TAB_ID:
                        CustomerDialog.createClone(MainFrame.this, selectedCustomer);
                        break;
                    case DETAIL_TAB_ID:
                        DetailDialog.createClone(MainFrame.this, selectedDetail);
                        break;
                }
            }
        });

        addToButtonControl(copyServiceButton);

        InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = getRootPane().getActionMap();

        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0), "INSERT");
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK), "NUMBER");

        actionMap.put("INSERT", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                addObject();
            }
        });
        actionMap.put("NUMBER", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                new ServiceNumberDialog(MainFrame.this).setVisible(true);
            }
        });

        deleteServiceButton = new JButton("Удалить", ServiceResourceContainer.DELETE_ICON);
        deleteServiceButton.setToolTipText("Удалить");
        addToButtonControl(deleteServiceButton);
        deleteServiceButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                switch (tabPane.getSelectedIndex()) {
                    case SERVICE_TAB_ID:
                        DAOLocator.getInstance().remove(selectedService);
//                        selectedService = null;
                        break;
                    case CUSTOMER_TAB_ID:
                        if (selectedCustomer.getServices().size() != 0) {
                            JOptionPane.showMessageDialog(null, "Невозможно удалить данного покупателя.",
                                    "Ошибка", JOptionPane.ERROR_MESSAGE);
                        } else {
                            DAOLocator.getInstance().remove(selectedCustomer);
                        }
//                        selectedCustomer = null;
                        break;
                    case DETAIL_TAB_ID:
                        if (DAOLocator.getInstance().getServices(selectedDetail).size() != 0) {
                            JOptionPane.showMessageDialog(null, "Невозможно удалить данную деталь.",
                                    "Ошибка", JOptionPane.ERROR_MESSAGE);
                        } else {
                            DAOLocator.getInstance().remove(selectedDetail);
                        }

                        break;
                }

                buttonControl(false);
            }
        });

        refreshButton = createButton(new AbstractAction("Обновить") {
            public void actionPerformed(ActionEvent e) {
                serviceTableModel.refreshModelAll();
                customersTableModel.refreshModelAll();
                detailsTableModel.refreshModelAll();

                serviceFilterPanel.applyData();
                detailsFilterPanel.applyData();
                customersFilterPanel.applyData();
            }
        }, null, ServiceResourceContainer.REFRESH);
        refreshButton.setToolTipText("Обновить");

        editServiceButton = new JButton("Редактировать", ServiceResourceContainer.EDIT_ICON);
        editServiceButton.setToolTipText("Редактировать");
        addToButtonControl(editServiceButton);
        editServiceButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                switch (tabPane.getSelectedIndex()) {
                    case SERVICE_TAB_ID:
                        ServiceDialog.editService(selectedService);
                        break;
                }
            }
        });

        emptyPanel = initializeEmptyPanel();
        serviceCompletePanel = initializeServiceCompletePanel();

        buttonControl(false);

        panel.add(UIHelper.createBorderLayoutPanel(
                new JComponent[]{
                        UIHelper.hBox(3, filterButton, 6, initializeCurrentUserPanel()),
//                        UIHelper.packInShiftedPanel(progressBar, 7, 7, 10, 10),
                        UIHelper.hBox(3, viewButton, 7, "|", 7, refreshButton, serviceCompletePanel, 1, emptyPanel, 3)
                },
                new Object[]{
                        BorderLayout.LINE_START,
//                        BorderLayout.CENTER,
                        BorderLayout.LINE_END
                }
        ), BorderLayout.CENTER);

        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0));

        return panel;
    }

    private void copyObject() {
        switch (tabPane.getSelectedIndex()) {
            case SERVICE_TAB_ID:
                if (selectedService != null) {
                    Service newService = selectedService.copyService();
                    newService.setSystemUser(SettingsStorage.getUserSettings().getCurrentUser());
                    DAOLocator.getInstance().add(newService);

                    ServiceDialog.editService(newService);
                    serviceFilterPanel.applyData();
                }
                break;
            case CUSTOMER_TAB_ID:
                CustomerDialog.createCustomer(this);
                customersFilterPanel.applyData();
                break;
            case DETAIL_TAB_ID:
                DetailDialog.createDetail(this, null);
                detailsFilterPanel.applyData();
                break;
        }
    }

    private void addObject() {
        switch (tabPane.getSelectedIndex()) {
            case SERVICE_TAB_ID:
                ServiceDialog.createService();
                serviceFilterPanel.applyData();
                break;
            case CUSTOMER_TAB_ID:
                CustomerDialog.createCustomer(this);
                customersFilterPanel.applyData();
                break;
            case DETAIL_TAB_ID:
                DetailDialog.createDetail(this, null);
                detailsFilterPanel.applyData();
                break;
        }
    }

    private JPanel initializeEmptyPanel() {
        JPanel panel = new JPanel();
        panel.add(CommonUIHelper.createVerticalBox(25));
        return panel;
    }

    private JPanel initializeServiceCompletePanel() {
        JPanel panel = new JPanel();

        printButton = new JButton(new AbstractAction("Печать", ServiceResourceContainer.PRINTER) {
            public void actionPerformed(ActionEvent e) {
                InputStream jasperInputStream = ServiceResourceContainer.class.getResourceAsStream("report/serviceReport.jasper");

                Map<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("MODEL", selectedService.getModelName());
                parameters.put("STATE", selectedService.getStampState());
                parameters.put("BARCODE", formatBarcode(selectedService));
                parameters.put("TECHNIC", selectedService.getTechNames());
                parameters.put("GUARANTY", selectedService.getGuarantyId());
                parameters.put("PHONE", selectedService.getOwner().getPhone());
                parameters.put("INTEGRITY", selectedService.getCompleteness());
                parameters.put("SERIAL_NUMBER", selectedService.getSerialNumber());
                parameters.put("ADDRESS", selectedService.getOwner().getAddress());
                parameters.put("CUSTOMER_DEFECT", selectedService.getOwnerDefect());
                parameters.put("SERVICE_DEFECT", selectedService.getMasterDefect());
                parameters.put("TECHNICAL_NAME", selectedService.getTechModelName());
                parameters.put("CUSTOMER", selectedService.getOwner().getExtendedName());
                parameters.put("ORDER_DATE", AuroraConstants.DATE_FORMAT_NORMAL.format(selectedService.getDateService()));
                parameters.put("DATE_PRODUCE", AuroraConstants.DATE_FORMAT_NORMAL.format(selectedService.getDateProduce()));

                try {
                    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperInputStream,
                            parameters, new JRTableModelDataSource(new DefaultTableModel(new Object[][]{{"1"},{"2"}}, new Object[]{"1"})));
                    ReportViewer.view(jasperPrint, "Отчет заказ-наряд");
                } catch (JRException e1) {
                    e1.printStackTrace();
                }


                /*File exportFile = new File("data/archive/service-" + selectedService.getId() + ".xls");
                try {
                    ExcelExporter.export(exportFile, selectedService);
                    Desktop.getDesktop().open(exportFile);
                } catch (BiffException e1) {
                    throw new RuntimeException("Ошибка экспортирования: " + exportFile.getAbsolutePath(), e1);
                } catch (IOException e1) {
                    throw new RuntimeException("Ошибка экспортирования: " + exportFile.getAbsolutePath(), e1);
                }*/
            }
        });

        serviceCompleteButton = new JButton(new AbstractAction("", ServiceResourceContainer.COMPLETE) {
            public void actionPerformed(ActionEvent e) {
                CompleteServiceDialog.completeService(selectedService);
            }
        });

        clientTookStuffButton = new JButton(new AbstractAction("", ServiceResourceContainer.CLIENT_TAKE_STUFF) {
            public void actionPerformed(ActionEvent e) {
                new ClientTakeStuffDialog(selectedService, MainFrame.this, new com.silverhaze.commons.ui.dialogs.DialogConnector<Date>() {
                    public void objectSelected(Date obj) {
                    }
                }).setVisible(true);
            }
        });

        panel.add(CommonUIHelper.createHorizontalBox(
                3, "|", 7,
                serviceCompleteButton, 5, clientTookStuffButton, 7, "|", 7, printButton
        ));
        serviceCompleteButton.setToolTipText("Завершить сервис");

        addToButtonControl(serviceCompleteButton);
        addToButtonControl(clientTookStuffButton);
        addToButtonControl(printButton);

        return panel;
    }

    private Long formatBarcode(Service selectedService) {
        Long id = selectedService.getId();

        while(id <= 9999999999L){
            id *= 10;
        }

        return id;
    }

    public JPanel initializeCurrentUserPanel() {
        JPanel currentUserPanel = new JPanel(new BorderLayout());

        Box hBox = Box.createHorizontalBox();
        hBox.add(Box.createHorizontalStrut(3));
        hBox.add(new JLabel("|"));
        hBox.add(Box.createHorizontalStrut(6));
        hBox.add(new JLabel(ServiceResourceContainer.CURRENT_USER));
        hBox.add(Box.createHorizontalStrut(4));
        hBox.add(new JLabel(UIStringConstants.CURRENT_USER + ": "));
        hBox.add(Box.createHorizontalStrut(4));
        hBox.add(new JLabel("<html><b>" + getCurrentUserName() + "</b></html>"));

        currentUserPanel.add(hBox, BorderLayout.CENTER);
        return currentUserPanel;
    }

    private String getCurrentUserName() {
        return SettingsStorage.getUserSettings().getCurrentUser().getLogin();
    }

    private void addToButtonControl(JButton btn) {
        if (buttonControl == null) {
            buttonControl = new ArrayList<JButton>();
        }

        buttonControl.add(btn);
    }

    private void buttonControl(boolean enabled) {
        for (JButton btn : buttonControl) {
            btn.setEnabled(enabled);
        }
    }

    public JProgressBar getProgressBar() {
        return progressBar;
    }

    @Override
    public void handleEvent(UIEvent event) {
        if (event instanceof UIUpdateEntitiesEvent) {
            UIUpdateEntitiesEvent classChanged = (UIUpdateEntitiesEvent) event;
            Class<? extends ObjectEntity> changedEntityClass = classChanged.getChangedEntityClass();

            if (Service.class.equals(changedEntityClass)) {
                serviceTableModel.fillData(DAOLocator.getInstance().getServices());
                serviceFilterPanel.applyData();
            } else if (Customer.class.equals(changedEntityClass)) {
                customersTableModel.fillData(DAOLocator.getInstance().getCustomers());
                customersFilterPanel.applyData();
            } else if (Detail.class.equals(changedEntityClass)) {
                detailsTableModel.fillData(DAOLocator.getInstance().getDetails());
                detailsFilterPanel.applyData();
            }
        }
    }
}
